package db

import (
	"github.com/google/uuid"
	"github.com/jinzhu/gorm"
	"sola/common"
	"time"
)

type Tag struct {
	common.BaseModel
	TagId              string `json:"tag_id" uri:"tag_id" gorm:"size:36;NOT NULL"`
	TagName            string `json:"tag_name" gorm:"size:64;NOT NULL"`
	SvgName            string `json:"svg_name" gorm:"size:64"`
	AuthorId           string `json:"author_id" gorm:"size:36"`
	AuthorName         string `json:"author_name" gorm:"size:64"`
	AuthorNickName     string `json:"author_nick_name" gorm:"size:64"`
	UpdateUserId       string `json:"update_user_id" gorm:"size:36"`
	UpdateUserName     string `json:"update_user_name" gorm:"size:64"`
	UpdateUserNickName string `json:"update_user_nick_name" gorm:"size:64"`
	Status             string `json:"status"`
	Changeable         bool   `json:"changeable"`
}

func (tag *Tag) BeforeCreate(scope *gorm.Scope) error {
	return scope.SetColumn("tag_id", uuid.New().String())
}

func (tag *Tag) BeforeSave(scope *gorm.Scope) error {
	return scope.SetColumn("updated_at", time.Now())
}

func CountTag(baseSearchModel *common.BaseSearchModel) (count int) {
	searchDB := db.Table("tags").Where("tag_name like ? and status like ?",
		"%"+baseSearchModel.Name+"%", "%"+baseSearchModel.Status+"%")
	if baseSearchModel.UserId != "" {
		searchDB = searchDB.Where("author_id = ?", baseSearchModel.UserId)
	}
	searchDB.Count(&count)
	return
}

func GetTagList(searchModel *common.BaseSearchModel) (tags []*Tag) {
	searchDB := db.Table("tags").Where("tag_name like ? and status like ?",
		"%"+searchModel.Name+"%", "%"+searchModel.Status+"%")
	if searchModel.UserId != "" {
		searchDB = searchDB.Where("author_id = ?", searchModel.UserId)
	}
	if searchModel.Limit > 0 {
		searchDB = searchDB.Offset((searchModel.Page - 1) * searchModel.Limit).Limit(searchModel.Limit)
	}
	if searchModel.Sort != "" {
		searchDB = searchDB.Order(searchModel.Sort)
	}
	searchDB.Find(&tags)
	return tags
}

func GetTagByTagId(tag *Tag) {
	searchDB := db.Table("tags").Where("tag_id = ?", tag.TagId)
	searchDB.First(tag)
	return
}
